package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.AuthLoginRequest;
import com.ruoyi.livedemo.dto.AuthRegisterRequest;
import com.ruoyi.livedemo.dto.LoginResponse;
import com.ruoyi.livedemo.dto.UserProfileView;
import com.ruoyi.livedemo.entity.User;
import com.ruoyi.livedemo.entity.UserProfile;
import com.ruoyi.livedemo.mapper.UserMapper;
import com.ruoyi.livedemo.mapper.UserProfileMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserMapper userMapper;
    private final UserProfileMapper userProfileMapper;
    private final TokenService tokenService;
    private final ProfileService profileService;
    private final PasswordEncoder passwordEncoder;

    @Transactional
    public User register(AuthRegisterRequest request) {
        if (userMapper.findByUsername(request.getUsername()) != null) {
            throw new IllegalArgumentException("用户名已存在");
        }
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
        user.setDisplayName(request.getDisplayName());
        user.setEmail(request.getEmail());
        userMapper.insert(user);

        UserProfile profile = new UserProfile();
        profile.setUserId(user.getId());
        profile.setPartnerName(request.getDisplayName());
        profile.setSelfIntroduction("欢迎来到甜蜜生活记事本");
        userProfileMapper.insert(profile);

        user.setPasswordHash(null);
        return user;
    }

    public LoginResponse login(AuthLoginRequest request, String userAgent) {
        User user = userMapper.findByUsername(request.getUsername());
        if (user == null || !passwordEncoder.matches(request.getPassword(), user.getPasswordHash())) {
            throw new IllegalArgumentException("用户名或密码不正确");
        }
        String token = tokenService.issueToken(user, userAgent);
        user.setPasswordHash(null);
        UserProfileView view = profileService.loadProfile(user.getId());
        return new LoginResponse(token, user, view);
    }

    public void logout(String token) {
        tokenService.invalidate(token);
    }

    @Transactional
    public void updateDisplayName(Long userId, String displayName) {
        if (!StringUtils.hasText(displayName)) {
            throw new IllegalArgumentException("昵称不能为空");
        }
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        user.setDisplayName(displayName);
        userMapper.update(user);
    }
}
